import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { Toast } from 'antd-mobile'
import { doctorService } from '../../services/doctorService'
import type { Doctor } from '../../data/mockDoctors'
import { filterDoctorsByDepartment } from '../../data/mockDoctors'

function Index() {
  const navigate = useNavigate()
  // 科室状态管理，默认选中妇产科
  const [activeDepartment, setActiveDepartment] = useState<Department>('妇产科')
  // 页面滚动状态
  const [isScrolled, setIsScrolled] = useState(false)
  // 顶部导航栏引用
  const headerRef = useRef<HTMLElement>(null)

  // 所有科室列表，使用as const确保类型安全
  const departments = [
    '妇产科', '儿科', '皮肤科', '心血管内科', '呼吸内科', '神经内科', '消化内科', '骨科'
  ] as const

  // 定义科室类型，基于departments数组
  type Department = typeof departments[number]

  const handleDepartmentChange = (department: Department): void => {
    setActiveDepartment(department)
  }

  // 监听滚动事件
  useEffect(() => {
    const handleScroll = () => {
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop
      setIsScrolled(scrollTop > 10)
    }

    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [])

  // 根据当前科室从接口拉取医生列表
  // useEffect(() => {
  //   const fetchDoctors = async () => {
  //     try {
  //       setLoading(true)
  //       setError(null)
  //       const params: DoctorListParams = {
  //         pageCode: '1',
  //         pageSize: '10',
  //         admin: activeDepartment as string
  //       }
  //       const res = await getDoctorList(params)
  //       const payload: unknown = (res as { data: unknown }).data
  //       let parsed: Doctor[] = []
  //       if (Array.isArray(payload)) {
  //         parsed = payload as Doctor[]
  //       } else if (payload && typeof payload === 'object') {
  //         const maybe = payload as { data?: unknown; list?: unknown }
  //         if (Array.isArray(maybe.data)) parsed = maybe.data as Doctor[]
  //         else if (Array.isArray(maybe.list)) parsed = maybe.list as Doctor[]
  //       }
  //       setDoctors(parsed)
  //     } catch (e: unknown) {
  //       setDoctors([])
  //       const msg = e instanceof Error ? e.message : '获取医生列表失败'
  //       setError(msg)
  //     } finally {
  //       setLoading(false)
  //     }
  //   }
  //   fetchDoctors()
  // }, [activeDepartment])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [displayDoctors, setDisplayDoctors] = useState<Doctor[]>([])
  const [loadingMore, setLoadingMore] = useState(false)
  const [hasMore, setHasMore] = useState(true)
  const [followedDoctors, setFollowedDoctors] = useState<Set<string>>(new Set())
  useEffect(() => {
    const fetchDoctors = async () => {
      setLoading(true)
      setError(null)
      
      try {
        await doctorService.fetchDoctors()
        // 重置分页状态
        doctorService.resetPagination()
        // 获取第一页数据
        const filteredFirstPage = filterDoctorsByDepartment(doctorService.getAllDoctors(), activeDepartment)
        setDisplayDoctors(filteredFirstPage)
        setHasMore(doctorService.getPaginationState().hasMore)
        console.log('====================================');
        console.log('医生数据获取成功');
        console.log('====================================');
      } catch (error) {
        console.error('获取医生数据失败:', error)
        setError('获取医生数据失败')
      } finally {
        setLoading(false)
      }
    }
    fetchDoctors()
  }, [])

  // 科室切换时更新显示数据
  useEffect(() => {
    if (doctorService.getAllDoctors().length > 0) {
      doctorService.resetPagination()
      
      // 使用本地筛选
      const filteredDoctors = filterDoctorsByDepartment(doctorService.getAllDoctors(), activeDepartment)
      setDisplayDoctors(filteredDoctors)
      setHasMore(filteredDoctors.length > 5)
      console.log(`📋 ${activeDepartment}科室医生数量:`, filteredDoctors.length)
    }
  }, [activeDepartment])

  // 初始化关注状态
  useEffect(() => {
    const savedDoctors = localStorage.getItem('followedDoctors')
    if (savedDoctors) {
      const doctors = JSON.parse(savedDoctors)
      const followedNames = new Set<string>(doctors.map((d: { name: string }) => d.name))
      setFollowedDoctors(followedNames)
    }
  }, [])

  // 检查医生是否被关注
  const isDoctorFollowed = (doctorName: string): boolean => {
    return followedDoctors.has(doctorName)
  }

  // 处理关注/取消关注医生
  const handleFollowDoctor = (doctor: Doctor) => {
    const doctorName = doctor.doctorname
    const isFollowed = isDoctorFollowed(doctorName)
    
    if (isFollowed) {
      // 取消关注
      const newFollowed = new Set(followedDoctors)
      newFollowed.delete(doctorName)
      setFollowedDoctors(newFollowed)
      
      // 从localStorage移除
      const savedDoctors = localStorage.getItem('followedDoctors')
      if (savedDoctors) {
        const doctors = JSON.parse(savedDoctors)
        const updatedDoctors = doctors.filter((d: { name: string }) => d.name !== doctorName)
        localStorage.setItem('followedDoctors', JSON.stringify(updatedDoctors))
        // 触发自定义事件，通知其他组件数据已更新
        window.dispatchEvent(new CustomEvent('followedDoctorsChanged'))
      }
    } else {
      // 添加关注
      const newFollowed = new Set(followedDoctors)
      newFollowed.add(doctorName)
      setFollowedDoctors(newFollowed)
      
      // 添加到localStorage
      const doctorToAdd = {
        id: doctor.doctorid || Date.now().toString(),
        name: doctor.doctorname,
        avatar: doctor.socoimage,
        title: doctor.doctorposition || '主治医师',
        department: doctor.socoadmin,
        hospital: doctor.hospital || '东莞市第八人民医院',
        rating: doctor.doctorgood || 99,
        isFollowed: true,
        lastMessage: '点击开始问诊',
        lastMessageTime: new Date().toLocaleString('zh-CN')
      }
      
      const savedDoctors = localStorage.getItem('followedDoctors')
      const doctors = savedDoctors ? JSON.parse(savedDoctors) : []
      doctors.push(doctorToAdd)
      localStorage.setItem('followedDoctors', JSON.stringify(doctors))
      // 触发自定义事件，通知其他组件数据已更新
      window.dispatchEvent(new CustomEvent('followedDoctorsChanged'))
    }
  }

  // 上拉加载更多医生
  const handleLoadMore = async () => {
    if (loadingMore || !hasMore) return

    setLoadingMore(true)
    try {
      await doctorService.loadMoreDoctors()
      // 使用本地筛选来获取新数据
      const allDoctors = doctorService.getAllDoctors()
      const filteredNewDoctors = filterDoctorsByDepartment(allDoctors, activeDepartment)
      setDisplayDoctors(prev => [...prev, ...filteredNewDoctors])
      setHasMore(doctorService.getPaginationState().hasMore)
    } catch (error) {
      console.error('加载更多医生失败:', error)
    } finally {
      setLoadingMore(false)
    }
  }

  // 滚动监听
  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget
    if (scrollHeight - scrollTop <= clientHeight + 100 && !loadingMore && hasMore) {
      handleLoadMore()
    }
  }
  return (
    <div className="home-page">
      {/* 顶部导航栏 */}
      <header
        ref={headerRef}
        className={`top-header ${isScrolled ? 'scrolled' : ''}`}
      >
        <div className="header-left">
          <div className="logo-container" onClick={() => navigate('/home')}>
            <div className="logo-icon">
              <svg viewBox="0 0 24 24" fill="currentColor" className="medical-icon">
                <path d="M12 2L13.09 8.26L20 9L13.09 9.74L12 16L10.91 9.74L4 9L10.91 8.26L12 2Z"/>
                <path d="M19 14L20 20L14 19L13 13L19 14Z"/>
                <path d="M5 14L6 20L12 19L13 13L5 14Z"/>
              </svg>
            </div>
            <div className="logo-text">
              <span className="app-name">妙手医生</span>
              <span className="dot">·</span>
              <span className="sub-name">妙手互联网医院</span>
            </div>
          </div>
        </div>
      </header>

      {/* 搜索栏 */}
      <div className="search-section">
        <div className="search-bar" onClick={() => navigate('/search')}>
          <span className="search-icon">🔍</span>
          <input
            type="text"
            placeholder="搜索医生、医院、药品、疾病症状"
            className="search-input"
            readOnly
          />
        </div>
      </div>

      {/* 热线信息 */}
      <div className="hotline-info">
        <span className="speaker-icon">🔊</span>
        <div className="hotline-scroll-container">
          <div className="hotline-scroll-content">
            <span className="hotline-text">川市政府热线0951-12345 妙手互联网医院热线400-078</span>
            <span className="hotline-text">心理咨询热线400-161-9995 健康咨询热线400-123-4567</span>
            <span className="hotline-text">川市政府热线0951-12345 妙手互联网医院热线400-078</span>
          </div>
        </div>
      </div>

      {/* 快速功能卡片 */}
      <div className="quick-features">
        <div className="feature-card" onClick={() => navigate('/yapp')}>
          <div className="feature-icon appointment">📅</div>
          <h3>预约挂号</h3>
          <p>30W+专家入驻</p>
        </div>
        <div className="feature-card" onClick={() => {
          // 设置快速问诊的初始数据
          localStorage.setItem('quickConsultation', JSON.stringify({
            type: 'quick',
            title: '极速问诊',
            description: '平均3分钟接诊，快速解决您的健康问题'
          }))
          // 临时直接跳转到 /message，绕过 antd-mobile Toast 在 React 19 下的问题
          navigate('/message')
        }}>
          <div className="feature-icon consultation">
            💬
            <span className="fast-badge">快</span>
          </div>
          <h3>极速问诊</h3>
          <p>平均3分钟接诊</p>
        </div>
        <div className="feature-card">
          <div className="feature-icon prescription">💊</div>
          <h3>复诊开方</h3>
          <p>慢病续方送到家</p>
        </div>

      </div>

      {/* 专家问诊区域 */}
      <div className="expert-section">
        <div className="section-header">
          <h2>我要问专家</h2>
          <span className="more-link">更多{'>'}</span>
        </div>

        {/* 科室标签 */}
        <div className="department-tabs">
          {departments.map((dept) => (
            <span
              key={dept}
              className={`dept-tab ${activeDepartment === dept ? 'active' : ''}`}
              onClick={() => handleDepartmentChange(dept)}
            >
              {dept}
            </span>
          ))}
        </div>

        {/* 当前科室信息 */}
        <div className="current-department">
          <h3 className="dept-title">{activeDepartment}专家</h3>
          <p className="dept-desc">为您推荐{activeDepartment}领域的专业医生</p>
        </div>

        {/* 加载状态 */}
        {loading && (
          <div className="loading-state">
            <div className="loading-spinner"></div>
            <p>加载中...</p>
          </div>
        )}

        {/* 错误状态 */}
        {error && (
          <div className="error-state">
            <p>⚠️ {error}</p>
          </div>
        )}
        {/* 医生列表 */}
        <div className="doctors-list" onScroll={handleScroll}>
          {displayDoctors.map((i, index) => (
            <div key={index} className="doctor-card">
              {/* 医生头像和基本信息 */}
              <div className="doctor-avatar">
                <img src={i.socoimage} alt={i.doctorname} className="avatar" />
                <div className="status-info">
                  <span className={`status ${i.doctorstate === '在线' ? 'online' : 'grade'}`}>
                    {i.doctorstate}
                  </span>
                </div>
              </div>

              {/* 医生信息 */}
              <div className="doctor-info">
                {/* 医生头部信息 */}
                <div className="doctor-header">
                  <h3 className="doctor-name">{i.doctorname}</h3>
                  <span className="doctor-title">{i.doctorposition || '主治医师'}</span>
                  {i.doctorstate === '三甲' && <span className="hospital-grade">三甲</span>}
                </div>

                {/* 医院和科室信息 */}
                <p className="hospital">
                  {i.hospital || '东莞市第八人民医院'}(东莞... {i.socoadmin}
                </p>

                {/* 咨询类型 */}
                <div className="consultation-types">
                  <span className="consultation-btn">图文咨询</span>
                  <span className="consultation-btn">电话咨询</span>
                  {index % 2 === 1 && <span className="consultation-btn">视频咨询</span>}
                </div>

                {/* 专长描述 */}
                <p className="specialty">
                  擅长: {i.doctordescword}
                  <span className="expand-icon">⌄</span>
                </p>

                {/* 统计数据 */}
                <div className="doctor-stats">
                  <span>好评率<span className="highlight">{i.doctorgood || 99}%</span></span>
                  <span className="divider">|</span>
                  <span>锦旗<span className="highlight">3</span></span>
                  <span className="divider">|</span>
                  <span>浏览人次<span className="highlight">{i.doctorid || 11942}</span></span>
                </div>

                {/* 底部操作区 */}
                <div className="doctor-footer">
                  <div className="price">¥{i.doctorprice || 15}<span className="price-unit">起</span></div>
                  <div className="action-buttons">
                    <button 
                      className={`follow-btn ${isDoctorFollowed(i.doctorname) ? 'followed' : ''}`}
                      onClick={(e) => {
                        e.stopPropagation()
                        handleFollowDoctor(i)
                      }}
                    >
                      <span className="follow-icon">
                        {isDoctorFollowed(i.doctorname) ? '✓' : '+'}
                      </span>
                      {isDoctorFollowed(i.doctorname) ? '已关注' : '关注'}
                    </button>
                    <button className="ask-doctor-btn" onClick={() => navigate(`/details?name=${encodeURIComponent(i.doctorname)}&avatar=${encodeURIComponent(i.socoimage)}&title=${encodeURIComponent(i.doctorposition || '主治医师')}&dept=${encodeURIComponent(i.socoadmin)}&hospital=${encodeURIComponent(i.hospital || '东莞市第八人民医院')}&specialty=${encodeURIComponent(i.doctordescword || '暂无专长描述')}`)}>问医生</button>
                  </div>
                </div>
              </div>
            </div>
          ))}
          
          {/* 加载更多状态 */}
          {loadingMore && (
            <div className="loading-more">
              <div className="loading-spinner"></div>
              <p>加载中...</p>
            </div>
          )}
          
          {/* 没有更多数据 */}
          {!hasMore && displayDoctors.length > 0 && (
            <div className="no-more-data">
              <p>没有更多医生了</p>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default Index
